package com.info3k.server.resetpassword;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.info3k.server.EmailService;
import com.info3k.server.PMF;
import com.info3k.server.domain.UserP;
import com.info3k.server.utils.Tools;

public class ResetPassword extends HttpServlet {

	private PersistenceManager persistence;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

	response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.println("<HTML>");
	out.println("  <HEAD><TITLE>Activate account</TITLE></HEAD>");
	out.println("  <BODY>");
	
	String username = request.getParameter("username");
	String key = request.getParameter("recoveryKey");
	
	if(username!=null && key!=null){
		Boolean act = resetPassword(username, key);
		if(act==null) {
			out.println("Can't find user in database!");
		} else if(act) {
			out.println("<p>Password reset successfully!</p><p>You will receive email with new password.</p>");
		}
	} else {
		out.println("Invalid username or registration key!");
	}
	
	out.println("  </BODY>");
	out.println("</HTML>");
	out.flush();
	out.close();
	}
	
	public Boolean resetPassword(String username, String key) {
		persistence = PMF.get().getPersistenceManager();
		Key k = KeyFactory.createKey(UserP.class.getSimpleName(), Long.valueOf(key));
		UserP userP = getUserByKey(k);
		if(userP!=null){
			String newPassword = Tools.getRandomString(8);
			
			EmailService emailService = new EmailService();
			emailService.sendEmail("New password", "<p>Hi " + userP.getUsername() + ",<br><br>Your new password is: " + newPassword + "</p><p><a href=\"http://info-3k.appspot.com/\"/>Log in here</a></p>", userP.getEmail(), userP.getUsername());
			
			userP.setPassword(Tools.getMD5(newPassword));

			persistence.makePersistent(userP);
			persistence.close();
			return true;
		}
		return null;
	}
	
	private UserP getUserByKey(Key key){
		Query q = persistence.newQuery("select from " + UserP.class.getName() + " where id == :keys");
		
		List<UserP> usersP = (List<UserP>)q.execute(key);
		
		if(usersP.size()>0) return usersP.get(0); 
		return null;
	}

}
